<?php

namespace app\api\controller\wanlshop;

use app\api\model\wanlshop\Withdraw;
use app\api\model\wanlshop\WithdrawalCash as WithdrawalCashModel;
use app\api\service\wanlshop\WithdrawalCash;
use app\common\controller\Api;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\Request;
use app\api\model\wanlshop\ActCashBack;

class Withdrawal extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    // 提现model
    protected $withdrawalCashModel = null;

    // 提现服务
    protected $withdrawalCashService = null;

    // 活动返现服务
    protected $actCashBackService = null;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->withdrawalCashService = new WithdrawalCash();
        $this->withdrawalCashModel = new WithdrawalCashModel();
        $this->actCashBackService = new ActCashBack();
    }

    /**
     * 提现列表
     * @return void
     */
    public function list()
    {
        $this->request->filter(['strip_tags']);
        $this->checkMethod(1);

        // 页码
        $page = $this->request->get('page', 1);

        // 每页显示的条数
        $pageSize = $this->request->get("pageSize", 10);

        $type = $this->request->get("type", 1);
        if (!in_array($type, [1, 2, 3, 4])) {
            $this->error('参数错误');
        }

        $params = [
            'user_id' => $this->auth->id,
            'type' => $type
        ];
        if (in_array($type, [1, 2, 4])) {
            $response = (new WithdrawalCashModel())->list($params, $pageSize);
        } else {
            $response = (new \app\api\service\wanlshop\ActCashBack())->myWithdrawalCashLists($this->auth->id, $page, $pageSize);
        }
        $this->success('成功', $response, 1);
    }

    /**
     * 提现申请保存
     * @return void
     * @throws Exception
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function save()
    {
        $this->request->filter(['strip_tags']);
        $this->checkMethod(2);
        $params = $this->request->post();

        if (empty($params['amount']) || $params['amount'] < 0) {
            $this->error('提现金额错误');
        }
        if (empty($params['type']) || !in_array($params['type'], [1, 2, 3, 4])) {
            $this->error('提现类型错误');
        }
        //1-商品旧物提现(换购)，2-余额提现，3-活动提现 4-转介绍
        if (in_array($params['type'], [1, 2, 4])) {
            $res = WithdrawalCashModel::handle($this->auth->id, $params);
        } else {
            $res = (new Withdraw())->actWithdrawHandle($this->auth->id, $params);
        }

        if ($res !== true) {
            $this->error("操作失败,$res");
        }

        $this->success('提现申请成功');
    }
}